package cn.memset.code.jcf;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class CollectionExample {
    public static void main(String[] args) {
        listSort();
    }

    public static void collectionForEach() {
        Collection<String> list = Arrays.asList("Guangdong", "Zhejiang", "Jiangsu");

        // for 语句
        for (String s : list) {
            System.out.println(s);
        }

        // forEach 方法 + lambda表达式
        list.forEach(s -> System.out.println(s));

        // forEach 方法 + 方法引用
        list.forEach(System.out::println);
    }

    public static void collectionRemoveIf() {
        List<String> provinces = new ArrayList<>(Arrays.asList("Guangdong", "Jiangsu", "Guangxi", "Jiangxi", "Shandong"));

        boolean removed = provinces.removeIf(s -> {
            return s.startsWith("G");
        });

        System.out.println(removed);
        System.out.println(provinces);
    }

    public static void listReplaceAll() {
        List<String> provinces = Arrays.asList("Guangdong", "Jiangsu", "Guangxi", "Jiangxi", "Shandong");
        provinces.replaceAll(s -> s.toUpperCase());
        System.out.println(provinces);
    }

    public static void listSort() {
        List<String> list = Arrays.asList("Guangdong", "Zhejiang", "Jiangsu", "Xizang", "Fujian", "Hunan", "Guangxi");

        // 对省份进行排序，首先按照长度排序，如果长度一样，则按照字母顺序排序
        list.sort((first, second) -> {
            int lenDiff = first.length() - second.length();
            return lenDiff == 0 ? first.compareTo(second) : lenDiff;
        });

        list.forEach(s -> System.out.println(s));
    }
}
